#include <iostream>
#include <vector>

using namespace std;

// 检查当前位置 (row, col) 是否可以放置皇后
bool isSafe(int row, int col, const vector<int>& board) {
    for (int i = 0; i < row; ++i) {
        // 检查同一列
        if (board[i] == col) return false;
        // 检查对角线
        if (abs(board[i] - col) == abs(i - row)) return false;
    }
    return true;
}

// 递归函数，尝试在每一行放置皇后
void solveNQueens(int row, int n, vector<int>& board, vector<vector<string>>& solutions) {
    if (row == n) {
        // 找到一个解，将其转换为棋盘表示
        vector<string> solution(n, string(n, '.')); // 初始化棋盘
        for (int i = 0; i < n; ++i) {
            solution[i][board[i]] = 'Q'; // 放置皇后
        }
        solutions.push_back(solution); // 添加到解集中
        return;
    }

    // 尝试在当前行的每一列放置皇后
    for (int col = 0; col < n; ++col) {
        if (isSafe(row, col, board)) {
            board[row] = col; // 记录当前行的皇后位置
            solveNQueens(row + 1, n, board, solutions); // 递归处理下一行
            board[row] = -1; // 回溯，撤销当前行的皇后位置
        }
    }
}

// 主函数，解决 N 皇后问题
vector<vector<string>> solveNQueens(int n) {
    vector<vector<string>> solutions; // 存储所有解
    vector<int> board(n, -1); // 记录每一行的皇后位置
    solveNQueens(0, n, board, solutions); // 从第 0 行开始递归
    return solutions;
}

// 打印所有解
void printSolutions(const vector<vector<string>>& solutions) {
    for (const auto& solution : solutions) {
        for (const string& row : solution) {
            cout << row << endl;
        }
        cout << "-----------------" << endl;
    }
}

int main() {
    int n;
    cout << "Enter the number of queens (N): ";
    cin >> n;

    vector<vector<string>> solutions = solveNQueens(n);

    if (solutions.empty()) {
        cout << "No solution exists for N = " << n << endl;
    } else {
        cout << "Total solutions: " << solutions.size() << endl;
        printSolutions(solutions);
    }

    return 0;
}